package zxs.sino.elite.hub.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import zxs.sino.elite.hub.model.form.LoginForm;
import zxs.sino.elite.hub.service.AdminAuthService;
import zxs.sino.elite.hub.utils.R;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 管理员认证管理
 *
 * @author zhang
 * @date 2025-06-30 20:51:41
 */
@RestController
@RequestMapping("auth/admin")
@RequiredArgsConstructor
public class AdminAuthController {

    private final AdminAuthService adminAuthService;

    /**
     * 验证码
     */
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = adminAuthService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public R login(@RequestBody LoginForm loginForm) {
        String token = adminAuthService.login(loginForm);
        return R.ok().put("token", token);
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R logout() {
        adminAuthService.logout();
        return R.ok();
    }
}
